<template>
  <div>
    <div id="qrcode"></div>
    <!-- 优惠券列表 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="优惠券名称：">
        <el-input
          v-model="queryForm.name"
          placeholder="请输入优惠券名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="优惠券类型：">
        <el-select
          @change="seachData"
          v-model="queryForm.coupon_type"
          placeholder="请选择所属科目"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option
            v-for="(item, index) in selectArr.coupon_type"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select
          @change="seachData"
          v-model="queryForm.status"
          placeholder="请选择所属科目"
        >
          <el-option label="全部" :value="null"></el-option>
          <el-option label="关闭" :value="0"></el-option>
          <el-option label="开启" :value="1"></el-option>
          <el-option label="失效" :value="2"></el-option>
          <!-- <el-option
            v-for="(item,index) in selectArr.status"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>-->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="seachData()">搜索</el-button>
        <el-button type="primary" @click="addUpdateCourse()"
          >新增优惠券</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      border
      :show-header="headerNone"
      style="width: 100%"
      header-cell-class-name="thead"
      @row-click="toAddCoupon"
    >
      <el-table-column prop="date" label="优惠券名称">
        <template slot-scope="scope">
          <b>{{ scope.row.name }}</b>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="价格">
        <template slot-scope="scope">
          <div class="u-box-hover">{{ scope.row.price }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="类型">
        <template slot-scope="scope">
          <div>
            {{ filterArr('coupon_type', scope.row.coupon_type) || '无' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="券销售额">
        <template slot-scope="scope">
          <div>{{ scope.row.total_amout }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="购券数">
        <template slot-scope="scope">
          <div>{{ scope.row.buy_count }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="券使用数">
        <template slot-scope="scope">
          <div>{{ scope.row.use_count }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="创建人">
        <template slot-scope="scope">
          <div>{{ scope.row.creator_name }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <div @click.stop="1">
            <b>发布状态</b>
            <el-switch
              v-model="scope.row.status"
              @change="switchChange($event, scope.row.id)"
            ></el-switch>
            <div>
              <a @click="downLoad(scope.row)">下载码</a>
              <a @click="clone(scope.row)">复制链接</a>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>
<script>
import jquery from 'jquery'
import QRCode from 'qrcodejs2'
import { queyEnumByTableName } from '@/api/api.js'
import {
  getCouponList,
  getActivityCouponResource,
  updateCouponStatus
} from '@/api/coupon.js'
export default {
  data () {
    return {
      queryForm: {
        name: '',
        coupon_type: '',
        status: ''
      },
      pageSize: 10,
      pageIndex: 1,
      totalPage: 0,
      selectArr: {
        coupon_type: []
      },
      tableData: [],
      headerNone: true,
      qrcode: null
    }
  },
  activated () {
    this.getSelectData()
  },
  methods: {
    toAddCoupon (e) {
      this.$router.push({ name: 'add-coupon', query: { id: e.id } })
    },
    // 下拉菜单过滤
    filterArr (field, val) {
      let arr = this.selectArr[field]
      let label
      arr.map(item => {
        if (parseInt(val) === parseInt(item.value)) {
          label = item.label
        }
        if (item.children && item.children.length > 0) {
          item.children.map(item2 => {
            if (parseInt(val) === parseInt(item2.value)) {
              label = item.label
            }
          })
        }
      })
      return label
    },
    addUpdateCourse () {
      this.$router.push({ name: 'add-coupon' })
    },
    // 下载
    downLoad (e, fileName = '二维码下载.png', content = '') {
      this.qrcode = new QRCode('qrcode', {
        width: 500,
        height: 500, // 高度
        text: e.url, // 二维码内容
        render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
      })
      setTimeout(() => {
        let img = jquery('#qrcode').find('img')[0].src
        jquery('#qrcode img').remove()
        let aLink = document.createElement('a')
        let blob = this.base64ToBlob(img) // new Blob([content]);
        let evt = document.createEvent('HTMLEvents')
        evt.initEvent('click', true, true) // initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = fileName
        aLink.href = URL.createObjectURL(blob)
        aLink.click()
      }, 800)
    },
    // base64转blob
    base64ToBlob (code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length

      let uInt8Array = new Uint8Array(rawLength)

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },

    clone (e) {
      var tag = document.createElement('input')
      tag.setAttribute('id', 'cp_zdy_input')
      tag.value = e.url
      document.getElementsByTagName('body')[0].appendChild(tag)
      document.getElementById('cp_zdy_input').select()
      document.execCommand('copy')
      document.getElementById('cp_zdy_input').remove()
      this.$message({
        message: '复制成功!',
        type: 'success'
      })
    },
    async switchChange (e, id) {
      let res = await updateCouponStatus({
        'nice_activity_coupon.id': id,
        'nice_activity_coupon.status': e ? 1 : 0
      })
      if (!res[0]) {
        return
      }
      this.getTableData()
    },
    seachData () {
      this.pageIndex = 1
      this.getTableData()
    },
    changeGrade (e) {
      this.queryForm.term = null
      if (e === null) {
        this.gradeLabel = '全部'
      } else {
        this.selectArr.grade.map(item => {
          if (item.value === e) {
            this.gradeLabel = item.label
          }
        })
      }
      this.seachData()
    },
    // 获取下拉菜单数据
    async getSelectData () {
      let res = await getActivityCouponResource({})
      if (res[0]) {
        return
      }
      let arr = res[1].data
      Object.keys(this.selectArr).forEach(item => {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].fieldName === item) {
            this.selectArr[item] = arr[i].sourceData.child
          }
        }
      })
      this.selectArr = JSON.parse(
        JSON.stringify(this.selectArr)
          .split('display_value')
          .join('label')
          .split('child')
          .join('children')
          .split('t_id')
          .join('value')
      )
      this.getTableData()
    },
    // 获取表数据
    async getTableData () {
      let res = await getCouponList({
        'page.currPage': this.pageIndex,
        'page.pageSize': this.pageSize,
        'nice_activity_coupon.name': this.queryForm.name,
        'nice_activity_coupon.coupon_type': this.queryForm.coupon_type,
        'nice_activity_coupon.status': this.queryForm.status
      })
      if (res[0]) {
        return
      }
      this.totalPage = res[1].data.pageList.totalCount
      this.tableData = res[1].data.pageList.list
      this.tableData.map(item => {
        item.status === 1 ? (item.status = true) : (item.status = false)
      })
    },
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getTableData()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getTableData()
    }
  }
}
</script>
<style scoped>
#qrcode {
  display: none;
}
</style>
